//
//  DetailViewController.m
//  SplitForce
//
//  Created by Dave Carroll on 6/20/10.
//  Copyright Salesforce.com 2010. All rights reserved.
//

#import "DetailViewController.h"
#import "RootViewController.h"
#import	"RelatedListTable.h"

#import "zkDescribeLayout.h"
#import "zkDescribeLayoutResult.h"
#import "zkDescribeLayoutButtonSection.h"
#import "zkDescribeLayoutSection.h"
#import "zkDescribeLayoutButton.h"
#import "zkRelatedList.h"
#import "zkRelatedListSort.h"
#import "zkRelatedListColumn.h"
#import "zkDescribeLayoutItem.h"
#import "zkDescribeLayoutRow.h"
#import "zkDescribeLayoutComponent.h"
#import "DetailTableEdit.h"

@interface DetailViewController ()
@property (nonatomic, retain) UIPopoverController *popoverController;
@end



@implementation DetailViewController

@synthesize toolbar, popoverController, detailItem, detailDescriptionLabel;

@synthesize editView, detailLayoutView,editTable ;
@synthesize lblAccountName, lblStreet, lblCity, lblZip, lblState, lblCountry;
@synthesize txtAccountName, txtStreet, txtCity, txtZip, txtState, txtCountry;

@synthesize layoutTable ,relatedTable;

static UISegmentedControl *segmentedControl;

- (void)viewDidLoad {
	NSLog(@"view did load detailview controller");

	NSArray *segmentTextContent = [NSArray arrayWithObjects:	
								   NSLocalizedString(@"Detail", @""), 
								   NSLocalizedString(@"Related List", @""), 
								   NSLocalizedString(@"Edit", @""),nil];
	
	segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
	segmentedControl.selectedSegmentIndex = 0;
	segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	segmentedControl.frame = CGRectMake(0, 0, 400, 33.0);
	[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
	UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
	[segmentedControl release];

	UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:	UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
	
	[self.toolbar setItems:[NSArray arrayWithObjects:spacer,segmentBarItem,nil]];
	
	// cleanup 
	[segmentedControl release];
	[segmentBarItem release];
	[spacer release];
}

-(void)addSubViews {
	// Detail view 
	layoutTable = [[DetailTable alloc] initWithStyle:UITableViewStylePlain];
		
	// related lists 
	relatedTable = [[RelatedListTable alloc] initWithStyle:UITableViewStylePlain];
	
	// edit view
	editTable = [[DetailTableEdit alloc] initWithStyle:UITableViewStylePlain];
	
	[self.view addSubview:editTable.view];  
	[self.view addSubview:relatedTable.view]; 
	[self.view addSubview:layoutTable.view];  // add this one as the default
	
	/* 
	 * each subview must accomidate the toolbar (x and height), adjust these now 
	 * http://stackoverflow.com/questions/2669651/uitableview-manual-scrolling-to-the-last-row
	 */
	CGRect	pp = layoutTable.view.frame;
	pp.origin.y = self.toolbar.frame.size.height;
	pp.size.height = pp.size.height - self.toolbar.frame.size.height;
	layoutTable.view.frame = pp;
	NSLog(@"layoutTable h:%f w:%f",layoutTable.view.frame.size.height,layoutTable.view.frame.size.width);
	
	CGRect	rtPos = relatedTable.view.frame;
	rtPos.origin.y = self.toolbar.frame.size.height ;//+ pp.size.height;
	relatedTable.view.frame = rtPos;
	
	CGRect	edPos = editTable.view.frame;
	edPos.origin.y = self.toolbar.frame.size.height;
	edPos.size.height = edPos.size.height - self.toolbar.frame.size.height;
	
	editTable.view.frame = edPos;
	NSLog(@"editTable h:%f w:%f",editTable.view.frame.size.height,editTable.view.frame.size.width);
	
}
#pragma mark -
#pragma mark Managing the detail item

/*
 When setting the detail item, update the view and dismiss the popover controller if it's showing.
 */
- (void)setDetailItem:(id)newDetailItem {
	if (detailItem != newDetailItem) {
		[detailItem release];
     detailItem = [newDetailItem retain];
	}
	[layoutTable setDetailItem:detailItem];
	
	[relatedTable setDetailItem:detailItem];

	[editTable setDetailItem:detailItem];
	
	if (popoverController != nil) {
		[popoverController dismissPopoverAnimated:YES];
	}        
}

- (IBAction)segmentAction:(id)sender
{
	// The segmented control was clicked, handle it here 
	UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
	NSLog(@"Segment clicked: %d", segmentedControl.selectedSegmentIndex);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1.0];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[self view] cache:YES];

	switch (segmentedControl.selectedSegmentIndex) {
		case 0: // Detail
			[editTable endEditing];
			[self.view bringSubviewToFront:layoutTable.view];			
			break;
			
		case 1: // Related list
			[editTable endEditing];
			[self.view bringSubviewToFront:relatedTable.view];			
			break;
			
		case 2: // Edit
			[self.view bringSubviewToFront:editTable.view];		
			[segmentedControl removeSegmentAtIndex:3 animated:YES];
			[segmentedControl insertSegmentWithTitle:@"Save" 
											atIndex:3 
											animated:YES];
			break;
		case 3:  // Save the changes
			[editTable endEditing];
			[segmentedControl removeSegmentAtIndex:3 animated:YES];
			[editTable saveDetailItem];
			
			// relaod the changed data on the detail page
			[layoutTable.tableView reloadData];
			
			[self.view bringSubviewToFront:layoutTable.view];
			
			break;
		default:
			break;
	}
	[UIView commitAnimations];
}
/*
-(IBAction)showEditView:(id)sender 
{
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1.0];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[self view] cache:YES];
	
	[self.view bringSubviewToFront:editTable.view];			

	[UIView commitAnimations];
}

-(IBAction)hideEditView:(id)sender {
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1.0];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:[self view] cache:YES];
	
	[self.view bringSubviewToFront:layoutTable.view];			

	
	[UIView commitAnimations];

	segmentedControl.selectedSegmentIndex = 0;

}
*/
-(IBAction)saveData:(id)sender {
	[self setEditing:NO];
	return;
}
- (void)failed:(id)err {
	NSLog(@"Error", "%@");
}
-(void)saveResultsReady:(NSArray *)results {
	
	ZKSaveResult *sr;
	NSEnumerator *e = [results objectEnumerator];
	SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];

	while (sr = [e nextObject]) {
		if ([sr success]) {
			if ([app.rootViewController.dataRows indexOfObject:detailItem] == NSNotFound) {
				// Need to add the new contact to the table.
				[detailItem setFieldValue:[sr id] field:@"Id"];
				 [app.rootViewController.dataRows insertObject:detailItem atIndex:0];
			} else {
				// Need to pass the changes back to the table.
				[app.rootViewController.dataRows replaceObjectAtIndex:[app.rootViewController.dataRows indexOfObject:detailItem] withObject:detailItem];
			}
			[app.rootViewController.tableView reloadData];
		} else {
			NSLog([sr message], "$@");
		}
	}
}
/*
- (void) setEditing:(BOOL) editing animated:(BOOL) animated {
	[super setEditing:editing animated:animated];
	
	if (!editing) {
		self.editButtonItem.title = @"Edit";
		self.title = @"Account Details";
		lblAccountName.text = txtAccountName.text;
		lblStreet.text = txtStreet.text;
		lblCity.text = txtCity.text;
		lblZip.text = txtZip.text;
		lblState.text = txtState.text;
		lblCountry.text = txtCountry.text;
		
		ZKSObject *account = (ZKSObject *)detailItem;
		[account setType:@"Account"];
		[account setFieldValue:txtAccountName.text field:@"Name"];
		[account setFieldValue:txtStreet.text field:@"ShippingStreet"];
		[account setFieldValue:txtCity.text field:@"ShippingCity"];
		[account setFieldValue:txtZip.text field:@"ShippingPostalCode"];
		[account setFieldValue:txtState.text field:@"ShippingState"];
		[account setFieldValue:txtCountry.text field:@"ShippingCountry"];
		
		NSArray *objects = [[NSArray alloc] initWithObjects:account, nil];
		SplitForceAppDelegate *app = (SplitForceAppDelegate *)[[UIApplication sharedApplication] delegate];
		ZKSforceClient *client = app.rootViewController.client;
		if ([account fieldValue:@"Id"] == nil) {
			[client createAsync:objects withDelegate:self];
		} else {
			[client updateAsync:objects withDelegate:self];
		}
		
		[self hideEditView:nil];
	} else {
		self.title = @"Edit Account";
		self.editButtonItem.title = @"Save";
		[self showEditView:nil];
	}
	
}*/

#pragma mark -
#pragma mark Split view support

- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc 
{
    
    barButtonItem.title = @"Root List";
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = pc;
}


// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem 
{
    
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = nil;
}


#pragma mark -
#pragma mark Rotation support

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}


#pragma mark -
#pragma mark View lifecycle

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.popoverController = nil;
}


#pragma mark -
#pragma mark Memory management

/*
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
*/

- (void)dealloc {
    [popoverController release];
    [toolbar release];
    
    [detailItem release];
    [detailDescriptionLabel release];
    [super dealloc];
}

@end
